package com.example.jinzproduct.controller;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.commons.entity.*;
import com.example.commons.utils.*;
import com.example.commons.vo.ExaminationsVo;
import com.example.commons.vo.TestPaperVo;
import com.example.jinzproduct.RedisUtil.RedisUtil;
import com.example.jinzproduct.entity.vo.ExaminationResultVo;
import com.example.jinzproduct.server.*;
import io.swagger.annotations.ApiOperation;
import lombok.extern.java.Log;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.*;

@Slf4j
@RestController
@RequestMapping("/jinZhiIndex/jzApi/examinations")
public class ApiExaminationsController   {

    @Autowired
    private KnowledgePointsService knowledgePointsService;
    @Autowired
    private DictService dictService;
    @Autowired
    private StuSignUpService stuSignUpService;
    @Autowired
    private ExaminationResultsService examinationResultsService;
    @Autowired
    private ExaminationBatchService examinationBatchService;
    @Autowired
    private ExaminationPaperService examinationPaperService;
    @Autowired
    private ExaminationQuestionsService examinationQuestionsService;
    @Autowired
    private ExaminationAnswerSheetService examinationAnswerSheetService;

    @Autowired
    private EvaluationService evaluationService;
    @Autowired
    private ExaminationAnswerSheetPracticeService examinationAnswerSheetPracticeService;
    @Autowired
    private LogService logService;
    @Autowired
    private ExceptionAddtimeService exceptionAddtimeService;
    @Autowired
    private CertificationBatchService certificationBatchService;
    @Autowired
    private TestPaperTemplateService testPaperTemplateService;
    @Autowired
    private TemplateDetailsService templateDetailsService;
    @Autowired
    private CertificateNewsService certificateNewsService;
    @Autowired
    private ItemBankService itemBankService;
    @Autowired
    private UserService userService;
        /**
         *  验证手机号是否存在 如果存在则进行绑定
         *
         * @Param: []
         * @Author: xzy
         * @Date: 2020-03-25
         */
    @GetMapping("/userPapers")
   // @Log("小程序获取考试批次接口")
    @ApiOperation(value = "考试程序端-考试信息接口", httpMethod = "GET", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public ApiResult<?> userPapers(String phone, String ticketNumber, String name, String idNumber) {

        Long userId= userService.userPhone(phone);
            if(userId==null||userId==0){
                return ApiResult.fail("手机号在系统中不存在！");
            }
        QueryWrapper<StuSignUpDO> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("name",name);
        queryWrapper.eq("ticket_number",ticketNumber);
        queryWrapper.eq("id_number",idNumber);
        StuSignUpDO stuSignUpDO =   stuSignUpService.getOne(queryWrapper);

        if (stuSignUpDO == null) {
            return ApiResult.fail("信息错误！");
        }
        stuSignUpDO.setUserId(userId);
        stuSignUpService.updateById(stuSignUpDO);

        return ApiResult.success();
    }

    /**
     *  成绩查询
     *  ticketNumber 考生编号
     *  idNumber     准考证号
     * @Param: []
     * @Author: xzy
     * @Date: 2022/9/14
     */
    @GetMapping("/achievementList")
    // @Log("小程序获取考试批次接口")
    @ApiOperation(value = "考试程序端-考试成绩查询接口", httpMethod = "GET", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public ApiResult<?> achievementList( String ticketNumber, String name, String idNumber,String year) {
        if(StringUtils.isBlank(year)){
            return ApiResult.fail("参数为空！");
        }

        List<Map> stuSignUpDO =   stuSignUpService.selcbatchList(ticketNumber,name,idNumber,year);
        for (int i=0;i<stuSignUpDO.size();i++){
            Date endTime = (Date) stuSignUpDO.get(i).get("endTime");
            // 指定格式化格式
            SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd");
           // System.out.println(f.format(endTime));
            stuSignUpDO.get(i).put("endTime",f.format(endTime));
            QueryWrapper<ExaminationAnswerSheetDO> queryWrapper=new QueryWrapper<>();
            queryWrapper.eq("stu_sign_id",stuSignUpDO.get(i).get("id"));

         ExaminationAnswerSheetDO sheetDO=   examinationAnswerSheetService.getOne(queryWrapper);
            if(sheetDO==null){
                stuSignUpDO.get(i).remove(i);
            }else {
                if(sheetDO.getState()==1){
                    stuSignUpDO.get(i).put("sheetId",sheetDO.getId());
                }else {
                    stuSignUpDO.get(i).remove(i);
                }

            }

        }

        return ApiResult.success(stuSignUpDO);
    }

    /**
     *  成绩详情
     * @Param: []
     * @Author: xzy
     * @Date: 2022/9/14
     */
    @GetMapping("/achievementDetails")
    // @Log("小程序获取考试批次接口")
    @ApiOperation(value = "考试程序端-考试成绩查询接口", httpMethod = "GET", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public ApiResult<?> achievementDetails( String id,String cbatchId) {

        if (id==null){
            return ApiResult.fail("参数不能为空！");
        }
        StuSignUpDO stuSignUpDO1 =   stuSignUpService.getById(id);
       ExaminationPaperDO examinationPaperDO1= examinationPaperService.getById(cbatchId);
        if(examinationPaperDO1==null){
            return ApiResult.fail("未查询到对应试卷！");
        }
        QueryWrapper<ExaminationAnswerSheetDO> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("stu_sign_id",stuSignUpDO1.getId());
        queryWrapper.eq("epaper_id",examinationPaperDO1.getId());
        ExaminationAnswerSheetDO examinationAnswerSheet = examinationAnswerSheetService.getOne(queryWrapper);
        if(examinationAnswerSheet==null){
            return ApiResult.fail("未查询到对应试卷！");
        }
        if(examinationAnswerSheet.getState()==0){
            return ApiResult.fail("还未阅卷，不能进行成绩查询！");
        }
        if (examinationAnswerSheet.getEpaperId() != null) {
            ExaminationPaperDO examinationPaperDO = examinationPaperService.getById(examinationAnswerSheet.getEpaperId());
            if (examinationPaperDO != null) {
                if(examinationPaperDO.getEbatchId()!=null){
                    ExaminationBatchDO examinationBatchDO= examinationBatchService.getById(examinationPaperDO.getEbatchId());
                    examinationAnswerSheet.setBatchName(examinationBatchDO.getName());
                }
                examinationAnswerSheet.setEpaperName(examinationPaperDO.getName());
            }
        }

        if (stuSignUpDO1 != null) {
                examinationAnswerSheet.setStuName(stuSignUpDO1.getName());
        }
        List<Map> maps = new ArrayList<>();
        Integer results = 0;
        Integer error = 0;
        Integer not=0;
        String[] ssr = examinationAnswerSheet.getAnswerList().split("\\{\"id\":\"");
        for (int i = 1; i < ssr.length; i++) {
            Map map = new HashMap();
            String[] ssc = ssr[i].split("\"}");
            for (int j = 0; j < ssc.length; j++) {
                String[] ssa = ssc[j].split("\",\"value\":\"");
                if (ssa.length > 1) {
                    ExaminationQuestionsDO examinationQuestionsDO = examinationQuestionsService.getById(ssa[0]);
                    map.put("titleNumber",examinationQuestionsDO.getTitleNumber());//题号
                    map.put("introduce",examinationQuestionsDO.getIntroduce());//题目内容
                    map.put("type",examinationQuestionsDO.getType());//题目内容
                    map.put("topicAnalysis","无");//题目解析
                    map.put("titleOptions",examinationQuestionsDO.getOptions());//题目选项
                    if (examinationQuestionsDO.getType() == 0 || examinationQuestionsDO.getType() == 2) {//单选题和判断题，答案唯一，可以不用拆解了
                        if (examinationQuestionsDO.getAnswers().equals(ssa[1])) {
                            map.put("answers",examinationQuestionsDO.getAnswers());//正确答案
                            map.put("options",ssa[1]);//考生选项
                            map.put("yesOrNo",true);
                           // System.out.println("正确单卷ID："+examinationQuestionsDO.getId());
                            results = results + examinationQuestionsDO.getScore();
                        }else{
                            map.put("answers",examinationQuestionsDO.getAnswers());//正确答案
                            map.put("options",ssa[1]);//考生选项
                            map.put("yesOrNo",false);
                            error++;
                        }
                    } else if (examinationQuestionsDO.getType() == 1) {//多选题因为答案有多个，需要循环判断一下是否包含该答案

                        boolean isRight=true;
                        if(ssa[1]==null||ssa[1]==""||ssa[1].length()==1){
                            isRight=false;
                        }else{
                            String[] ssb = ssa[1].substring(0,ssa[1].length()-2).split(";;");
                            String answer = examinationQuestionsDO.getAnswers();
                            if(ssb.length!=answer.split(";;").length){
                                isRight=false;
                            }else {
                                for (int n = 0; n < ssb.length; n++) {
                                    //if (ssb[n].equals("A") || ssb[n].equals("B") || ssb[n].equals("C") || ssb[n].equals("D") || ssb[n].equals("E") || ssb[n].equals("F")) {
                                    if (!answer.contains(ssb[n])) {
                                        isRight = false;
                                        break;
                                    }

                                }
                            }
                        }

                        if(isRight){
                            map.put("answers",examinationQuestionsDO.getAnswers());//正确答案
                            map.put("options",ssa[1]);//考生选项
                            map.put("yesOrNo",true);
                         //   System.out.println("正确单卷ID："+examinationQuestionsDO.getId());
                            results = results + examinationQuestionsDO.getScore();
                        }else{
                            error++;
                            map.put("answers",examinationQuestionsDO.getAnswers());//正确答案
                            map.put("options",ssa[1]);//考生选项
                            map.put("yesOrNo",false);
                        }
                    }
                    maps.add(map);
                }else if(ssa.length == 1 && !ssa[0].equals(",") && !ssa[0].equals("]")){
                    ExaminationQuestionsDO examinationQuestionsDO = examinationQuestionsService.getById(ssa[0]);
                    map.put("titleNumber",examinationQuestionsDO.getTitleNumber());//题号
                    map.put("type",examinationQuestionsDO.getType());//题号
                    map.put("introduce",examinationQuestionsDO.getIntroduce());//题目内容
                    map.put("titleOptions",examinationQuestionsDO.getOptions());//题目选项
                    map.put("answers",examinationQuestionsDO.getAnswers());//正确答案
                    map.put("options","");//考生选项
                    map.put("yesOrNo",false);
                    not++;
                    maps.add(map);
                }
            }
        }
        examinationAnswerSheet.setAnswerLists(maps);
        //分数
        examinationAnswerSheet.setScore(results);
        examinationAnswerSheet.setError(error);
        examinationAnswerSheet.setSuccess(maps.size()-(error+not));
        examinationAnswerSheet.setNotScored(not);


        //examinationAnswerSheet.setCreate_time();

        return   ApiResult.success(examinationAnswerSheet);
    }

    /**
     * 小程序考试批次接口
     *
     * @Description: 获取考试信息，包括考试名称、开考时间、结束时间、时长、考试须知，考试题型等介绍
     * @Param: []
     * @return: com.jinzhi.common.utils.ApiResult<?>
     * @Author: kl
     * @Date: 2020-03-25
     * examType 师资
     * 2  幼儿照护
     */
    @GetMapping("/appletsSelExamination")
   // @Log("小程序获取考试批次接口")
    @ApiOperation(value = "考试程序端-考试信息接口", httpMethod = "GET", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public ApiResult<?> appletsSelExamination(Integer examType) {
        //ExaminationsVo examinationsVo = examinationBatchService.selExaminations();
        if(examType==null){
            examType=1;
        }
        if(examType==1){
            List<ExaminationsVo> examinationsVos = examinationBatchService.selListExaminationsTeachers();

            if(examinationsVos != null && examinationsVos.size() > 0) {
                for(int i=0;i<examinationsVos.size();i++) {
                    Map<String, String> map = new HashMap<>();
                    map.put("name", "考试须知");
                    map.put("type", "exa_exam_notes");
                    String examNotes = dictService.selDicBy(map);
                    examinationsVos.get(i).setExamNotes(examNotes);

                    map.clear();
                    map.put("name", "考试提交成功页广告语");
                    map.put("type", "exam_bg");
                    String backGroundImage = dictService.selDicBy(map);
                    examinationsVos.get(i).setBackGroundImage(backGroundImage);
                    DateTimeFormatter sdf= DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

                    Instant instant = examinationsVos.get(i).getStartTime().toInstant();
                    ZoneId zoneId = ZoneId.systemDefault();
                    LocalDateTime localDateTime = instant.atZone(zoneId).toLocalDateTime();

                    Instant instante = examinationsVos.get(i).getEndTime().toInstant();
                    LocalDateTime localDateTimee = instante.atZone(zoneId).toLocalDateTime();

                    examinationsVos.get(i).setStartTimes( sdf.format(localDateTime));
                    examinationsVos.get(i).setEndTimes( sdf.format(localDateTimee));
                    //EhCacheUtil.put("selExamination", examinationsVo);
                }
                return ApiResult.success(examinationsVos);

            }else {
                return ApiResult.fail("暂无考试信息！");
            }
        }else {
            List<ExaminationsVo> examinationsVos = examinationBatchService.selListExaminationsNow();
          //  List<ExaminationsVo> examinationsVos = examinationBatchService.selListExaminationsTeachers();
            if(examinationsVos != null && examinationsVos.size() > 0) {
                for(int i=0;i<examinationsVos.size();i++) {
                    Map<String, String> map = new HashMap<>();
                    map.put("name", "考试须知");
                    map.put("type", "exa_exam_notes");
                    String examNotes = dictService.selDicBy(map);
                    examinationsVos.get(i).setExamNotes(examNotes);

                    map.clear();
                    map.put("name", "考试提交成功页广告语");
                    map.put("type", "exam_bg");
                    String backGroundImage = dictService.selDicBy(map);
                    examinationsVos.get(i).setBackGroundImage(backGroundImage);
                    DateTimeFormatter sdf= DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

                    Instant instant = examinationsVos.get(i).getStartTime().toInstant();
                    ZoneId zoneId = ZoneId.systemDefault();
                    LocalDateTime localDateTime = instant.atZone(zoneId).toLocalDateTime();

                    Instant instante = examinationsVos.get(i).getEndTime().toInstant();
                    LocalDateTime localDateTimee = instante.atZone(zoneId).toLocalDateTime();

                    examinationsVos.get(i).setStartTimes( sdf.format(localDateTime));
                    examinationsVos.get(i).setEndTimes( sdf.format(localDateTimee));
                    //EhCacheUtil.put("selExamination", examinationsVo);
                }
                return ApiResult.success(examinationsVos);

            }else {
                return ApiResult.fail("暂无考试信息！");
            }

        }


    }

    /**
     * 小程序考试批次接口
     *
     * @Description: 获取考试信息，包括考试名称、开考时间、结束时间、时长、考试须知，考试题型等介绍
     * @Param: []
     * @return: com.jinzhi.common.utils.ApiResult<?>
     * @Author: kl
     * @Date: 2020-03-25
     */
    @GetMapping("/appletsSelExaminationScreen")
  //  @Log("小程序获取所有筛选考试批次接口")
    @ApiOperation(value = "考试程序端-考试信息接口", httpMethod = "GET", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public ApiResult<?> appletsSelExaminationScreen() {
        //ExaminationsVo examinationsVo = examinationBatchService.selExaminations();
        List<ExaminationsVo> examinationsVos = examinationBatchService.selListExaminationsScreen();

        if(examinationsVos != null && examinationsVos.size() > 0) {
            for(int i=0;i<examinationsVos.size();i++) {
                Map<String, String> map = new HashMap<>();
                map.put("name", "考试须知");
                map.put("type", "exa_exam_notes");
                String examNotes = dictService.selDicBy(map);
                examinationsVos.get(i).setExamNotes(examNotes);

                map.clear();
                map.put("name", "考试提交成功页广告语");
                map.put("type", "exam_bg");
                String backGroundImage = dictService.selDicBy(map);
                examinationsVos.get(i).setBackGroundImage(backGroundImage);

                //EhCacheUtil.put("selExamination", examinationsVo);
            }
            return ApiResult.success(examinationsVos);
        }else {
            return ApiResult.fail("暂无考试信息！");
        }
    }

    /**
     * 考试程序端-考试信息接口
     *
     * @Description: 获取考试信息，包括考试名称、开考时间、结束时间、时长、考试须知，考试题型等介绍
     * @Param: []
     * @return: com.jinzhi.common.utils.ApiResult<?>
     * @Author: kl
     * @Date: 2020-03-25
     */
    @GetMapping("/selExamination")
  //  @Log("考试程序端-考试信息接口")
    @ApiOperation(value = "考试程序端-考试信息接口", httpMethod = "GET", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public ApiResult<?> selExamination() {
        //ExaminationsVo examinationsVo = examinationBatchService.selExaminations();
        List<ExaminationsVo> examinationsVos = examinationBatchService.selListExaminationsNow();
       // List<ExaminationsVo> examinationsVosceshi = examinationBatchService.selListExaminationsNowCeshi();
        //正式考试加上测试考试
       // examinationsVos.addAll(examinationsVosceshi);

        if(examinationsVos != null && examinationsVos.size() > 0) {
        	for(int i=0;i<examinationsVos.size();i++) {
        		Map<String, String> map = new HashMap<>();
        		map.put("name", "考试须知");
        		map.put("type", "exa_exam_notes");
        		String examNotes = dictService.selDicBy(map);
        		examinationsVos.get(i).setExamNotes(examNotes);

        		map.clear();
        		map.put("name", "考试提交成功页广告语");
        		map.put("type", "exam_bg");
        		String backGroundImage = dictService.selDicBy(map);
        		examinationsVos.get(i).setBackGroundImage(backGroundImage);

        		//EhCacheUtil.put("selExamination", examinationsVo);
        	}
          return ApiResult.success(examinationsVos);
        }else {
        	return ApiResult.fail("暂无考试信息！");
        }
    }

    /**
     * 考试程序端-考试信息接口 山东省职业技能竞赛
     *
     * @Description: 获取考试信息，包括考试名称、开考时间、结束时间、时长、考试须知，考试题型等介绍
     * @Param: []
     * @return: com.jinzhi.common.utils.ApiResult<?>
     * @Author: kl
     * @Date: 2020-03-25
     */
    @GetMapping("/selSdExamination")
    //@Log("考试程序端-考试信息接口")
    @ApiOperation(value = "考试程序端-考试信息接口", httpMethod = "GET", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public ApiResult<?> selSdExamination() {
        //ExaminationsVo examinationsVo = examinationBatchService.selExaminations();
        List<ExaminationsVo> examinationsVos = examinationBatchService.selListExaminationsNowJs();
        // List<ExaminationsVo> examinationsVosceshi = examinationBatchService.selListExaminationsNowCeshi();
        //正式考试加上测试考试
        // examinationsVos.addAll(examinationsVosceshi);
        if(examinationsVos != null && examinationsVos.size() > 0) {
            for(int i=0;i<examinationsVos.size();i++) {
                Map<String, String> map = new HashMap<>();
                map.put("name", "考试须知");
                map.put("type", "exa_exam_notes");
                String examNotes = dictService.selDicBy(map);
                examinationsVos.get(i).setExamNotes(examNotes);

                map.clear();
                map.put("name", "考试提交成功页广告语");
                map.put("type", "exam_bg");
                String backGroundImage = dictService.selDicBy(map);
                examinationsVos.get(i).setBackGroundImage(backGroundImage);

                //EhCacheUtil.put("selExamination", examinationsVo);
            }
            return ApiResult.success(examinationsVos);
        }else {
            return ApiResult.fail("暂无考试信息！");
        }
    }

    //将考生状态改为考试中
    @PostMapping("/changeState")
  //  @Log("考试程序端-考试登录接口")
    @ApiOperation(value = "考试程序端-考试登录接口", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public Object changeState(String id) {
        QueryWrapper<StuSignUpDO> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("id",id);
        StuSignUpDO stuSignUpDO =   stuSignUpService.getOne(queryWrapper);
    //	StuSignUpDO stuSignUpDO = stuSignUpService.findOneByKv("id",id);
    	stuSignUpDO.setState(8);
      boolean b=  stuSignUpService.updateById(stuSignUpDO);
        return b==true ? ApiResult.success("修改成功"):ApiResult.fail("修改状态失败");
    }

    //获取服务器系统时间
    @PostMapping("/getNowDateTime")
   // @Log("考试程序端-获取服务器时间")
    @ApiOperation(value = "考试程序端-获取服务器时间", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public Object getNowDateTime() {
            DateTimeFormatter df=DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            LocalDateTime localDateTime=LocalDateTime.now();
            Map map=new HashMap();
        map.put("time",df.format(localDateTime));
        return ApiResult.success(map);

    }

    /**
     * 考试程序端-考试登录接口
     *考生登录
     * @Description: 考试程序端考生登录获取考生信息，参数：考生姓名、身份证号、考号、考试批次id
     * @Param: [name, idCard, ticketNumber, id]
     * @return: com.jinzhi.common.utils.ApiResult<?>
     * @Author: kl
     * @Date: 2020-03-26
     */
    @PostMapping("/loginExamination")
  //  @Log("考试程序端-考试登录接口")
    @ApiOperation(value = "考试程序端-考试登录接口", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public ApiResult<?> loginExamination(String name, String idNumber, String ticketNumber, String id) {
    	if (StringUtils.isBlank(name)) {
            return ApiResult.lack("");//缺少参数
        }
        if (StringUtils.isBlank(idNumber)) {
            return ApiResult.lack("");//缺少参数
        }
        if (StringUtils.isBlank(ticketNumber)) {
            return ApiResult.lack("");//缺少参数
        }
        if (StringUtils.isBlank(id)) {
            return ApiResult.fail("暂无考试1！");
        }
        QueryWrapper<StuSignUpDO> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("name",name);
        queryWrapper.eq("ticket_number",ticketNumber);
        queryWrapper.eq("id_number",idNumber);
        queryWrapper.eq("cbatch_id",id);
        StuSignUpDO stuSignUpDO =   stuSignUpService.getOne(queryWrapper);

       // StuSignUpDO stuSignUpDO = stuSignUpService.findOneByKv("name", name, "ticket_number", ticketNumber,"id_number",idNumber,"cbatch_id",id);
        if (stuSignUpDO == null) {
            return ApiResult.fail("信息错误！");
        } else {
        	//String idNumber=stuSignUpDO.getIdNumber();
        	//String pw = ticketNumber.substring(ticketNumber.length()-4)+idNumber.substring(idNumber.length()-4);
        	//if(!pw.equals(password)) {
        	//	return ApiResult.fail("密码错误！");
        	//}
            ExaminationBatchDO examinationBatchDO = examinationBatchService.getById(Long.parseLong(id));

          if( !LocalDateTimeUtil.resultYesOrNo(LocalDateTime.now(),LocalDateTimeUtil.dateToDateTime(examinationBatchDO.getEndTime()))){
              return ApiResult.fail("考试已禁止进入！");
          }

            if (examinationBatchDO == null) {
                return ApiResult.fail("暂无考试2！");
            } else {
                if (examinationBatchDO.getId().equals(stuSignUpDO.getCbatchId())) {
                    if (stuSignUpDO.getState().equals(3) || stuSignUpDO.getState().equals(8)) {
                        //stuSignUpDO.setState(8);
                        boolean bbc = stuSignUpService.updateById(stuSignUpDO);
                        if (bbc) {
                            Map map = new HashMap();
                            map.put("stuSignId", stuSignUpDO.getId());//考生id
                            map.put("roomNumber", stuSignUpDO.getEallocationNum());//考场号
                            map.put("name", stuSignUpDO.getName());//考生姓名
                            map.put("batchId", examinationBatchDO.getId());//考生姓名

                            map.put("ticketNumber", stuSignUpDO.getTicketNumber());//考号
                            map.put("idCard", stuSignUpDO.getIdNumber());//身份证号码
                            map.put("photo", stuSignUpDO.getPhoto());//考生照片
                            map.put("seatNumber", stuSignUpDO.getTicketNumber().substring(stuSignUpDO.getTicketNumber().length() - 2));//座位号
                            map.put("state", stuSignUpDO.getState());//考生状态
                            map.put("nowDate", new Date());
                            Map<String, String> map1 = new HashMap<>();
                    		map1.put("name", "允许考试切屏次数");
                    		map1.put("type", "exam_allow_num");
                            map.put("allowNum", dictService.selDicBy(map1));
                            //添加认证码，认证码格式是： md5（"考号"+"YYMMDD"）
                            Date currentTime = new Date();
                            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
                            String dateString = formatter.format(currentTime);
                            String cookieCode = MD5Util.md5(stuSignUpDO.getTicketNumber(), dateString);
                            map.put("cookieCode", cookieCode);


                            QueryWrapper<DictDO> queryWrapperDic=new QueryWrapper<>();
                            queryWrapperDic.eq("type","exam_num");
                            DictDO dic =    dictService.getOne(queryWrapperDic);

                         //  dictService.findOneByKv("type" , "exam_num");
                            QueryWrapper<DictDO> queryWrapperDic1=new QueryWrapper<>();
                            queryWrapperDic1.eq("type","exam_num");
                            DictDO dic1 =    dictService.getOne(queryWrapperDic1);
                            //DictDO dic1 = dictService.findOneByKv("type" , "send_num");
                            map.put("time" , dic.getValue());
                            map.put("dates" , dic1.getValue());
                            map.put("examinationTime",getSubmitTime(examinationBatchDO.getStartTime())); //交卷时间
                            return ApiResult.success(map);
                        } else {
                            return ApiResult.fail("系统错误，请重试！");
                        }
                    } else {

                        if(stuSignUpDO.getState().equals(10)){
                            return ApiResult.fail("您已交卷成功，请耐心等待考试结果，有问题请联系技术人员！");
                        }
                        return ApiResult.fail("您已进入考试或状态异常，请与监考员联系！");
                    }
                } else {
                    return ApiResult.fail("暂无考试3！");
                }
            }
        }
    }

    /**
     * 考试程序端-考试试卷接口
     *
     * @Description: 查询试卷数据，包括试卷id、试卷编号、试卷名称、题目、选项、题号;
     * 参数：考试批次id
     * @Param: [id]
     * @return: com.jinzhi.common.utils.ApiResult<?>
     * @Author: kl
     * @Date: 2020-03-26
     */
    @PostMapping("/selTeacherExaminationPaper")
 //   @Log("考试程序端-考试试卷接口")
    @ApiOperation(value = "考试程序端-考试试卷接口", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public ApiResult<?> selTeacherExaminationPaper(String id) {
        if (StringUtils.isBlank(id)) {
            return ApiResult.fail("暂无试卷！");
        }
       // Map map = (Map) EhCacheUtil.get("examinationPaperDO" + id);
      //  if (map == null) {
            Map mapre = new HashMap();
            QueryWrapper<ExaminationPaperDO> queryWrapper=new QueryWrapper<>();
            queryWrapper.eq("ebatch_id",id);
            ExaminationPaperDO examinationPaperDO =  examinationPaperService.getOne(queryWrapper);
          //  ExaminationPaperDO examinationPaperDO = examinationPaperService.findOneByKv("ebatch_id", Long.parseLong(id), "state", 1);
            if (examinationPaperDO != null) {
                mapre.put("id", examinationPaperDO.getId());//试卷id
                mapre.put("name", examinationPaperDO.getName());//试卷名称
                mapre.put("numbers", examinationPaperDO.getNumbers());//试卷编号

                Map map1 = new HashMap();
                map1.put("epaperId", examinationPaperDO.getId());
               // List<ContractManagementEntity> tenderSnList = contractManagementService.
                // list(new QueryWrapper<ContractManagementEntity>().eq("tender_sn", item.getTenderSn()).eq("deleted_flag", 'N'));
                QueryWrapper<ExaminationQuestionsDO> queryWrapperList=new QueryWrapper<>();
                queryWrapperList.eq("epaper_id", examinationPaperDO.getId());
                List<ExaminationQuestionsDO> ExaminationQuestionsDOs
                        =examinationQuestionsService.list(queryWrapperList);
              //  List<ExaminationQuestionsDO> ExaminationQuestionsDOs = examinationQuestionsService.findByKv("epaper_id", examinationPaperDO.getId());

                // List<ExaminationQuestionsDO> ExaminationQuestionsDOs = examinationQuestionsService.findByKv("epaper_id", examinationPaperDO.getId());
                mapre.put("questions", ExaminationQuestionsDOs);//试卷试题

                EhCacheUtil.put("examinationPaperDO" + id, mapre);
                return ApiResult.success(mapre);
            } else {
                return ApiResult.fail("暂无试卷！");
            }
//        } else {
//            return ApiResult.success(map);
//        }
    }

    /**
     * 考试程序端-考试试卷接口
     *
     * @Description: 查询试卷数据，包括试卷id、试卷编号、试卷名称、题目、选项、题号;
     * 参数：考试批次id
     * @Param: [id]
     * @return: com.jinzhi.common.utils.ApiResult<?>
     * @Author: kl
     * @Date: 2020-03-26
     */
    @PostMapping("/selExaminationPaper")
    //@Log("考试程序端-考试试卷接口")
    @ApiOperation(value = "考试程序端-考试试卷接口", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public ApiResult<?> selExaminationPaper(String id) {
        if (StringUtils.isBlank(id)) {
            return ApiResult.fail("暂无试卷！");
        }
        Map map = (Map) EhCacheUtil.get("examinationPaperDO" + id);
        if (map == null) {
            Map mapre = new HashMap();
            QueryWrapper<ExaminationPaperDO> wrapper=new QueryWrapper<>();
            wrapper.eq("ebatch_id", Long.parseLong(id));
            wrapper.eq("state", 1);
            ExaminationPaperDO examinationPaperDO =     examinationPaperService.getOne(wrapper);
          //  ExaminationPaperDO examinationPaperDO = examinationPaperService.findOneByKv("ebatch_id", Long.parseLong(id), "state", 1);
            if (examinationPaperDO != null) {
                mapre.put("id", examinationPaperDO.getId());//试卷id
                mapre.put("name", examinationPaperDO.getName());//试卷名称
                mapre.put("numbers", examinationPaperDO.getNumbers());//试卷编号

                Map map1 = new HashMap();
                map1.put("epaperId", examinationPaperDO.getId());
                List<TestPaperVo> testPaperVos = examinationQuestionsService.selTestPaper(map1);
                mapre.put("questions", testPaperVos);//试卷试题

                EhCacheUtil.put("examinationPaperDO" + id, mapre);
                return ApiResult.success(mapre);
            } else {
                return ApiResult.fail("暂无试卷！");
            }
       } else {
            return ApiResult.success(map);
       }
    }

    /**
     * 考试程序端-考模拟考试试卷接口
     *  刷题
     * @Description: 获得模拟考试试卷数据，包括试卷id、试卷编号、试卷名称、限时、题目、选项、题号
     * 参数：考试批次id
     * @Param: [profile_id]  证书概况id
     * @Param: [grade]  证书等级 （0高级，1中级，2初级）
     * @return: com.jinzhi.common.utils.ApiResult<?>
     * @Author: kl
     * @Date: 2020-03-26
     */
    @PostMapping("/selTrainExaminationPaper")
   // @Log("考试程序端-考模拟考试试卷接口")
    @ApiOperation(value = "考试程序端-考模拟考试试卷接口", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public ApiResult<?> selTrainExaminationPaper(String profile_id,String  grade) {
        if (StringUtils.isBlank(profile_id)) {
            profile_id = "1241245212023312386L"; //当前默认为  幼儿照护职业技能等级证书
         }
        if (StringUtils.isBlank(grade)) {
            return ApiResult.fail("等级错误！");
        }else{
            if(!(grade.equals("0")||grade.equals("1")||grade.equals("2")))
                return ApiResult.fail("等级错误！");
        }
        String cn_id = "";
        int ty=0;

        Map mapdic=new HashMap();
             mapdic.put("type","tydic");
             mapdic.put("name","长沙托育配置");

        Date nowDate = new Date();
        String key = nowDate.getYear()+""+nowDate.getMonth()+""+nowDate.getDay()+""+nowDate.getHours()+""+nowDate.getMinutes()/10;
        //减少sql查询负担
        if(profile_id.equals("1241245212023312386")){//幼儿照护
            key+="幼儿照护"+grade;
            Map ehcacheMap = (Map)EhCacheUtil.get(key);
            if(ehcacheMap!=null){
                return ApiResult.success(ehcacheMap);
            }
            else{
                EhCacheUtil.remove((String)EhCacheUtil.get("LastTime幼儿照护"));
                EhCacheUtil.put("LastTime幼儿照护",key);
            }
            switch (grade){
                case "0":cn_id = "1241246900989841410";break;
                case "1":cn_id = "1241246701718458370";break;
                case "2":cn_id = "1241245991509544961";break;
            }
        }else if(profile_id.equals("1375327865662226434")){//产后恢复
            key+="产后恢复"+grade;
            Map ehcacheMap = (Map)EhCacheUtil.get(key);
            if(ehcacheMap!=null){
                return ApiResult.success(ehcacheMap);
            }
            else{
                EhCacheUtil.remove((String)EhCacheUtil.get("LastTime产后恢复"));
                EhCacheUtil.put("LastTime产后恢复",key);
            }
            switch (grade){
                case "0":cn_id = "1399199728653402113";break;
                case "1":cn_id = "1399199555814522882";break;
                case "2":cn_id = "1399199123935428609";break;
            }
        }else if(profile_id.equals("1522773009475420162")){//长沙市托育机构负责人模拟考试
            key+="长沙市托育机构"+grade;
            Map ehcacheMap = (Map)EhCacheUtil.get(key);
            if(ehcacheMap!=null){
               // return ApiResult.success(ehcacheMap);
            }
            else{
                EhCacheUtil.remove((String)EhCacheUtil.get("LastTime长沙市托育机构"));
                EhCacheUtil.put("LastTime长沙市托育机构",key);
            }
            switch (grade){
                case "2":cn_id = "1522773090287075329   ";break;
            }

            String dicty= dictService.selDicBy(mapdic);
            if(dicty.equals("1")){
                ty=1;
            }
            Map mapdics=new HashMap();
            mapdics.put("type","csyesno");
            mapdics.put("name","长沙托育刷题配置");
            String dictyc= dictService.selDicBy(mapdic);
            if(dictyc.equals("1")){
                return    ApiResult.fail("刷题练习结束！");
            }

        }else if(profile_id.equals("1522773009475485497")){//河南托育机构负责人模拟考试

            profile_id="1546681042605527042";
            key+="河南托育机构"+grade;
            Map ehcacheMap = (Map)EhCacheUtil.get(key);
            if(ehcacheMap!=null){
                // return ApiResult.success(ehcacheMap);
            }
            else{
                EhCacheUtil.remove((String)EhCacheUtil.get("LastTime河南托育机构"));
                EhCacheUtil.put("LastTime河南托育机构",key);
            }
            switch (grade){
                case "1":cn_id = "1546694751551283202";break;
                case "2":cn_id = "1546694751551283202";break;
            }

            String dicty= dictService.selDicBy(mapdic);
            if(dicty.equals("1")){
                ty=1;
            }

            Map mapdics=new HashMap();
            mapdics.put("type","hnyesno");
            mapdics.put("name","河南育刷题配置");
            String dictyc= dictService.selDicBy(mapdic);
            if(dictyc.equals("1")){
                return    ApiResult.fail("刷题练习结束！");
            }

        }else{
         return    ApiResult.fail("证书编号错误！");
        }

        Map mapre = new HashMap(); //返回值
        mapre.put("id", "000000");//试卷id
        mapre.put("name","");//试卷名称
        mapre.put("numbers", "");//试卷编号
        if(ty==1){
            mapre.put("endTime", DateTimeUtil.getPostponeTimesOradvanceTimes(new Date(),-4));//结束时间
        }else {
            mapre.put("endTime",DateTimeUtil.getPostponeTimesOradvanceTimes(new Date(),-1));//结束时间
        }


        ArrayList<Map> retQuestions = new ArrayList<>();
                    QueryWrapper<TestPaperTemplateDO> queryWrapper=new QueryWrapper<>();
                        queryWrapper.eq("type", 0);
                        queryWrapper.eq("news_id", cn_id);
                    TestPaperTemplateDO testPaperTemplateDO =  testPaperTemplateService.getOne(queryWrapper);

                  //  TestPaperTemplateDO testPaperTemplateDO = testPaperTemplateService.findOneByKv("type", 0, "news_id", cn_id);
                    if (testPaperTemplateDO == null) {
                        return  ApiResult.fail("未找到对应的试卷模板，请检查或重试！");
                    } else {
                        QueryWrapper<TemplateDetailsDO> templateDetailsDOsList=new QueryWrapper<>();
                        templateDetailsDOsList.eq("tptemplate_id", testPaperTemplateDO.getId());
                        List<TemplateDetailsDO> templateDetailsDOs = templateDetailsService.list(templateDetailsDOsList);

                        //List<TemplateDetailsDO> templateDetailsDOs = templateDetailsService.findByKv("tptemplate_id", testPaperTemplateDO.getId());
                        if (templateDetailsDOs != null && templateDetailsDOs.size() > 0) {
                            int th = 1;
                            //从题库中查询并将信息添加至试卷试题
                            for (TemplateDetailsDO templateDetailsDO : templateDetailsDOs) {
                                //暂时去除实操题的生成
                                if (templateDetailsDO.getType() < 3) {
                                        Map<Object, Object> map = new HashMap<>();
                                        map.put("kpointsId", templateDetailsDO.getKpointsId());//templateDetailsDO.getKpointsId()); 当前默认为空，不做限制
                                        map.put("profileId", profile_id);//certificationBatchDO.getProfileId());
                                        map.put("topicTypes", templateDetailsDO.getType());
                                        map.put("item_bank_type", "0"); //只用练习题  0：练习题;1：考试题;不加这条则取所有题库
                                        int titleNumber = 0;
                                        if (grade.equals("0")) { //certificateNewsDO.getGrade() == 0
                                            map.put("grade", "高级");
                                        } else if (grade.equals("1")) {//certificateNewsDO.getGrade() == 1
                                            map.put("grade", "中级");
                                        } else if (grade.equals("2")) {//certificateNewsDO.getGrade() == 2
                                            map.put("grade", "初级");
                                        }
                                    QueryWrapper<TemplateDetailsDO> templateDetailsDOQueryWrapper=new QueryWrapper<>();
                                    templateDetailsDOQueryWrapper.eq("kpoints_id",templateDetailsDO.getKpointsId());
                                    templateDetailsDOQueryWrapper.eq("tptemplate_id",templateDetailsDO.getTptemplateId());
                                    templateDetailsDOQueryWrapper.eq("type",templateDetailsDO.getType()+3);

                                    TemplateDetailsDO t = templateDetailsService.getOne(templateDetailsDOQueryWrapper);

                                       // TemplateDetailsDO t = templateDetailsService.findOneByKv("kpoints_id",templateDetailsDO.getKpointsId(),"tptemplate_id",templateDetailsDO.getTptemplateId(),"type",templateDetailsDO.getType()+3);
                                        if(t!=null){
                                            titleNumber=templateDetailsDO.getTitleNumber()+t.getTitleNumber();
                                        }else{
                                            titleNumber=templateDetailsDO.getTitleNumber();
                                        }

                                        if(ty==0){
                                            map.put("titleNumber",titleNumber );
                                        }else {

                                            map.put("titleNumber",400 );
                                        }

                                        List<Map<Object, Object>> maps = itemBankService.selRandList(map);//目前已经是根据单个知识点直接查询，已经调整了like查询了
                                       if(ty==1){
                                           for (int i = 0; i < maps.size(); i++) {
                                               Map testPaperMap = new HashMap();//试题明细
                                               testPaperMap.put("id",maps.get(i).get("bankId"));//examinationPaperDO1.getId()
                                               testPaperMap.put("topicTypes",maps.get(i).get("topicTypes"));
                                               testPaperMap.put("introduce",maps.get(i).get("topicContent").toString());
                                               testPaperMap.put("options",maps.get(i).get("options").toString());
                                               testPaperMap.put("answer",maps.get(i).get("rightKey").toString());
                                               testPaperMap.put("score",templateDetailsDO.getScore());
                                               testPaperMap.put("topicAnalysis",maps.get(i).get("topicAnalysis"));
                                               testPaperMap.put("resourceType",maps.get(i).get("resourceType"));
                                               testPaperMap.put("titleNumber",th);
                                               th+=1;
                                               retQuestions.add(testPaperMap);//添加试卷试题
                                           }
                                       }else {
                                           if (maps != null &&  maps.size() == titleNumber) {
                                               for (int i = 0; i < maps.size(); i++) {
                                                   Map testPaperMap = new HashMap();//试题明细
                                                   testPaperMap.put("id",maps.get(i).get("bankId"));//examinationPaperDO1.getId()
                                                   testPaperMap.put("topicTypes",maps.get(i).get("topicTypes"));
                                                   testPaperMap.put("introduce",maps.get(i).get("topicContent").toString());
                                                   testPaperMap.put("options",maps.get(i).get("options").toString());
                                                   testPaperMap.put("answer",maps.get(i).get("rightKey").toString());
                                                   testPaperMap.put("score",templateDetailsDO.getScore());
                                                   testPaperMap.put("topicAnalysis",maps.get(i).get("topicAnalysis"));
                                                   testPaperMap.put("resourceType",maps.get(i).get("resourceType"));
                                                   testPaperMap.put("titleNumber",th);
                                                   th+=1;
                                                   retQuestions.add(testPaperMap);//添加试卷试题
                                               }
                                           } else {
                                               String errorMsg="题库数量不足，无法生成考试！（"+templateDetailsDO.getKpointsId()+"）";
                                               return  ApiResult.fail(errorMsg);
                                           }
                                       }



                                }
                            }
                        } else {

                            return  ApiResult.fail("试卷模板详情信息有误或没有信息，生成试卷失败，请检查并稍后重试！");
                        }
                        mapre.put("questions", retQuestions);//添加试卷试题
                    }
      //  EhCacheUtil.put(key, mapre);
        return ApiResult.success(mapre);
    }

    /**
     * 考试程序端-考模拟考试试卷接口
     *
     * @Description: 获得模拟考试试卷数据，包括试卷id、试卷编号、试卷名称、限时、题目、选项、题号
     * 参数：考试批次id
     * @Param: [profile_id]  证书概况id
     * @Param: [grade]  证书等级 （0高级，1中级，2初级）
     * @return: com.jinzhi.common.utils.ApiResult<?>
     * @Author: kl
     * @Date: 2020-03-26
     */
    @PostMapping("/selYuyinExaminationPaper")
   // @Log("小程序端-育婴员模拟考试试卷接口")
    @ApiOperation(value = "小程序端-育婴员模拟考试试卷接口", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public ApiResult<?> selYuyinExaminationPaper() {
        String profile_id = "1379704595300278274"; //育婴员

        Map m = new HashMap<String,String>();
        m.put("name", "育婴员题库练习");
        m.put("type", "yuyin_brushTopic_on-off");
        String examNotes = dictService.selDicBy(m);
        if(!examNotes.equals("on")){
            return  ApiResult.fail("无法访问");
        }

        Map mapre = new HashMap(); //返回值
        mapre.put("id", "000000");//试卷id
        mapre.put("name","");//试卷名称
        mapre.put("numbers", "");//试卷编号
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date now = new Date();
        Date endTime = new Date(now .getTime() + 90*60*1000);//毫秒，共90分钟
        mapre.put("endTime",DateTimeUtil.getPostponeTimesOradvanceTimes(new Date(),-1));//结束时间
        ArrayList<Map> retQuestions = new ArrayList<>();

        QueryWrapper<ItemBankDO> itemList=new QueryWrapper<>();
        itemList.eq("profile_id", profile_id);
        itemList.eq("item_bank_type", "0");

        List<ItemBankDO> maps = itemBankService.list(itemList);

       // List<ItemBankDO> maps = itemBankService.findByKv("profile_id", profile_id,"item_bank_type", "0");//目前已经是根据单个知识点直接查询，已经调整了like查询了
        if (maps != null && maps.size() > 0) {
            for (int i = 0; i < maps.size(); i++) {
                //ExaminationQuestionsDO examinationQuestionsDO = new ExaminationQuestionsDO();
                Map testPaperMap = new HashMap();//试题明细

                testPaperMap.put("id",i+1);//examinationPaperDO1.getId()
                testPaperMap.put("topicTypes",maps.get(i).getTopicTypes());
                testPaperMap.put("introduce",maps.get(i).getTopicContent());
                testPaperMap.put("options",maps.get(i).getOptions());
                testPaperMap.put("answer",maps.get(i).getRightKey());
                testPaperMap.put("score",1);
                testPaperMap.put("topicAnalysis",maps.get(i).getTopicAnalysis());

                testPaperMap.put("resourceType",maps.get(i).getResourceType());
                testPaperMap.put("titleNumber",i+1);//题号
                retQuestions.add(testPaperMap);//添加试卷试题
            }
        } else {
            return  ApiResult.fail("题库中暂未题目，请检查并稍后重试！");
        }
        mapre.put("questions", retQuestions);//添加试卷试题

        return ApiResult.success(mapre);


    }

    /**
     * 考试模拟练习试卷提交
     *
     * @Description: 考生提交考卷；参数：考生id，试卷id，答卷集合
     * @Param: [stuSignId, epaperId, answerList]
     * @return: com.jinzhi.common.utils.ApiResult<?>
     * @Author: kl
     * @Date: 2020-03-27
     */
    @PostMapping("/selAnswerSheetPractice")
    @ApiOperation(value = "考试程序端-考试答卷提交接口", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public ApiResult<?> selAnswerSheetPractice(String mobile, String answerList,Long profile_id,Long  grade,Integer time) {
      if (StringUtils.isBlank(mobile)) {
            return ApiResult.lack("");//缺少参数
        }
//      if( !ValidUtils.isMobile(mobile)){
//          return ApiResult.lack("手机号格式错误");//缺少参数
//      }

//        if (StringUtils.isBlank(epaperId)) {
//            return ApiResult.lack("");//缺少参数
//             }
                    //提交试卷新增绑定考试批次字段
                    ExaminationAnswerPracticeSheetDO examinationAnswerSheetDO1 = new ExaminationAnswerPracticeSheetDO();
                    examinationAnswerSheetDO1.setEpaperId(profile_id);//试卷id
                    examinationAnswerSheetDO1.setGrade(grade);
                    examinationAnswerSheetDO1.setCreate_time(LocalDateTime.now());

                    examinationAnswerSheetDO1.setStuSignId(mobile);//考生id

                    examinationAnswerSheetDO1.setAnswerList(answerList);//答卷集合
                    examinationAnswerSheetDO1.setTime(time);
                     examinationAnswerSheetDO1.setUserid(JWTUtil.getUser().getId());
                    examinationAnswerSheetDO1.setProfile_id(profile_id);
                    boolean b = examinationAnswerSheetPracticeService.save(examinationAnswerSheetDO1);
                    if(b){
                        Map map=new HashMap();
                        map.put("id",examinationAnswerSheetDO1.getId());
                        return ApiResult.success(map);
                    }else {
                        return ApiResult.fail("试卷提交失败");
                    }

    }
    /**
     * 考试程序端-考试答卷提交接口
     *
     * @Description: 考生提交考卷；参数：考生id，试卷id，答卷集合
     * @Param: [stuSignId, epaperId, answerList]
     * @return: com.jinzhi.common.utils.ApiResult<?>
     * @Author: kl
     * @Date: 2020-03-27
     */
//    @PostMapping("/selAnswerSheet")
//    @ApiOperation(value = "考试程序端-考试答卷提交接口", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
//    public ApiResult<?> selAnswerSheet(String stuSignId, String epaperId, String answerList, String code) {
//        if (StringUtils.isBlank(stuSignId)) {
//            return ApiResult.lack("");//缺少参数
//        }
//        if (StringUtils.isBlank(epaperId)) {
//            return ApiResult.lack("");//缺少参数
//        }
//
//        StuSignUpDO stuSignUpDO = stuSignUpService.getById(Long.parseLong(stuSignId));
//        if (stuSignUpDO != null) {
//            //添加认证码，认证码格式是： md5（"考号"+"YYMMDD"）
//            Date currentTime = new Date();
//            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
//            String dateString = formatter.format(currentTime);
//            boolean bb = MD5Util.verify(stuSignUpDO.getTicketNumber(), dateString, code);
//            if (bb) {
//                QueryWrapper<ExaminationAnswerSheetDO> wrapper=new QueryWrapper<>();
//                wrapper.eq("epaper_id", epaperId);
//                wrapper.eq("stu_sign_id", stuSignId);
//                ExaminationAnswerSheetDO examinationAnswerSheetDO =   examinationAnswerSheetService.getOne(wrapper);
//
//             //   ExaminationAnswerSheetDO examinationAnswerSheetDO = examinationAnswerSheetService.getOne(new QueryWrapper<>().eq("epaper_id", epaperId).eq("stu_sign_id", stuSignId) );
//                if (examinationAnswerSheetDO != null) {
//                    return ApiResult.fail("试卷已提交，如有问题请联系监考员");
//                } else {
//                    //提交试卷新增绑定考试批次字段
//                    ExaminationAnswerSheetDO examinationAnswerSheetDO1 = new ExaminationAnswerSheetDO();
//                    examinationAnswerSheetDO1.setEpaperId(Long.parseLong(epaperId));//试卷id
//                    examinationAnswerSheetDO1.setStuSignId(Long.parseLong(stuSignId));//考生id
//                    examinationAnswerSheetDO1.setAnswerList(answerList);//答卷集合
//                    boolean b = examinationAnswerSheetService.save(examinationAnswerSheetDO1);
//                    if (b) {
//                        stuSignUpDO.setState(10);
//                        boolean bbc = stuSignUpService.updateById(stuSignUpDO);
//                        if (bbc) {
//                            return ApiResult.success("提交成功");
//                        } else {
//                            return ApiResult.fail("提交失败，请重试");
//                        }
//                    } else {
//                        return ApiResult.fail("提交失败，请重试！");
//                    }
//                }
//            } else {
//                saveLog("考试程序端-考试答卷提交接口", stuSignId + ";" + epaperId + ";" + answerList, stuSignUpDO.getUserId(), stuSignUpDO.getName());
//                return ApiResult.fail("信息错误，请重试");
//            }
//        } else {
//            saveLog("考试程序端-考试答卷提交接口", stuSignId + ";" + epaperId + ";" + answerList, -2L, "不明来历者");
//            return ApiResult.fail("信息错误，请重试");
//        }
//    }

    private void saveLog(String valuess, String params, Long id, String name) {
        LogDO sysLog = new LogDO();
        sysLog.setOperation(valuess + "，访问异常，请注意！");
        sysLog.setParams(params);
        HttpServletRequest request = HttpContextUtils.getHttpServletRequest();
        if (request != null) {
            sysLog.setMethod(request.getMethod() + " " + request.getRequestURI());
            // 设置IP地址
            sysLog.setIp(IPUtils.getIpAddr(request));
        }
        // 用户名
        sysLog.setUserId(id);
        sysLog.setUsername(name);
        sysLog.setTime(11);
        sysLog.setGmtCreate(new Date());
        // 保存系统日志
        logService.save(sysLog);
    }


    /**
     * 成绩查询接口
     * @param year
     * @param name
     * @param ticketNumber
     * @param idNumber
     * @return
     */
    @PostMapping("/selExaminationResult")
    @ResponseBody
    ApiResult<?> selExaminationResult(String year, String name, String ticketNumber, String idNumber) {
        Map map = new HashMap();
        if(year==null||year==""||ticketNumber==null||ticketNumber==""||idNumber==""||idNumber==null){
            return ApiResult.fail("查询信息不完整！");
        }
        map.put("name", name);
        map.put("ticketNumber", ticketNumber);
        map.put("idNumber", idNumber);
        map.put("year", year);
        List<ExaminationResultVo> examinationResultVo = examinationResultsService.selectByStu(map);
        if(examinationResultVo.size()<=0){
            return ApiResult.fail("未查询到成绩！");
        }
        for(ExaminationResultVo e : examinationResultVo){
            if(e.getBatchType()==2&&!e.getEbatchName().contains("师资")&&!e.getEbatchName().contains("考评员")&&!e.getEbatchName().contains("督导")&&!e.getEbatchName().contains("考务")&&!e.getEbatchName().contains("测试")){
                EvaluationDO eval = evaluationService.findOneByKv("admission_number",e.getTicketNumber());
                if(eval!=null){
                    e.setPracticalScore(eval.getPracticalOperation());
                }
            }
        }
        return ApiResult.success(examinationResultVo);
    }







    /**
     * 强制交卷配置接口
     */
    @GetMapping("/examSubmitNumber")
    public ApiResult examSubmitNumber(){
        Map c = (Map) RedisUtil.get("examSubmitNumber");
        if (c!=null){
            return ApiResult.success(c);
        }
        Map map =new HashMap();
        map.put("name","强制切屏次数控制");
        map.put("type","qpcs_kz");
        String number = dictService.selDicBy(map);
        Map rst = new HashMap();
        rst.put("examSubmitNumber",number);
        RedisUtil.set("examSubmitNumber",rst,18000); //五小时后失效重新获取
        return ApiResult.success(rst);
    }


    /**
     * 获取交卷时间与后台配置时间接口
     * @param date
     * @return
     */
    private Map getSubmitTime(Date date){
        Map c = (Map) RedisUtil.get("getSubmitTime");
        if (c!=null){
            return c;
        }
        Map ret =new HashMap();
        Map map =new HashMap();
        map.put("name","交卷时间控制");
        map.put("type","jjsj_kz");
        String jjsj = dictService.selDicBy(map);
        SimpleDateFormat dateFormat= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        long time = Integer.valueOf(jjsj)*60*1000;
        Date afterdate = new Date(date.getTime() + time); //交卷时间
        ret.put("submitTime",dateFormat.format(afterdate));
        ret.put("configurationTime",jjsj);
        RedisUtil.set("getSubmitTime",ret,18000); //五小时后失效重新获取
        return ret;
    }


}
